<script setup>
import 'animate.css'
import {nextTick, onMounted, onUnmounted, ref, watch} from "vue";
import {getFullProfile, getUserInfoApi} from "@/api/user.js";
import {host_custom} from "@/host.js";
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import axios from "axios";
import {userStore} from "@/stores/userStore.js";
import {checkFriendReqStatus, checkIfHasFriendRequest} from '@/api/friend';
import {friendService} from "@/service/friendService.js";
const userAction = userStore()
import emitter from "@/utils/EventBus.js";
import {timeToNumber} from "@/utils/timeToNumber.js";

const userProfile = ref({})

const user_id = ref(null)

const getUserProfiles = async (uid) => {
  const res = await getFullProfile(uid)
  if (res) {
    userProfile.value = res.data[0]
    console.log(res.data[0])
  }
}
const isFriend = ref(null)
const checkRelationship = async (uid) => {
  const res = await axios.get(host_custom+'/checkRelationship', {params: {uid_1: userAction.userInfo.id, uid_2: uid}})
  if (res.status === 200) {
    const [rs] = res.data
    isFriend.value = rs.count
  }
}

onMounted(()=> {
  window.addEventListener('resize', () => {
    cardVisible.value = false
    isShowSpinner.value = true
  })

  emitter.on('showMiniProfileCard', async (data)=> {
    isSentReq.value = false
    user_id.value = data.uid
    fixCardPosition(data)
    await showUserProfileCard()
    await getUserProfiles(data.uid)
    await getFriendReqStatus(data.uid)
    await checkRelationship(data.uid)
    await checkIfFriendRequest(data.uid)
    isShowSpinner.value = false
  })
})

onUnmounted(()=> {
  emitter.off('showMiniProfileCard')
})

const isSentReq = ref(false)

const addFriend = async () => {
  const res = await friendService().sendFriendRequest(user_id.value)
  if (res) isSentReq.value = true
}

const getFriendReqStatus = async (uid) => {
  if (userAction.userInfo.id !== uid) {
    const res = await checkFriendReqStatus(userAction.userInfo.id, uid)
    isSentReq.value = res.data[0].count
  }
}

const cardTop = ref(0)
const cardLeft = ref(0)
const cardVisible = ref(false)


const isShowAcceptDiv = ref(false)
const checkIfFriendRequest = async (uid) => {
  const res = await checkIfHasFriendRequest(uid, userAction.userInfo.id)
  if (res.status === 200) {
    const [data] = res.data
    isShowAcceptDiv.value = data.count
  }
}

const fixCardPosition = (data) => {
  const { boundingClientRect } = data

  if (window.innerHeight - boundingClientRect.top < 210) {
    cardTop.value = boundingClientRect.top - (210 - (window.innerHeight - boundingClientRect.top))
  } else {
    cardTop.value = boundingClientRect.top
  }

  if (window.innerWidth - boundingClientRect.right < 310) {
    cardLeft.value = boundingClientRect.left - 310
  } else {
    cardLeft.value = boundingClientRect.right + 10
  }
}

const closeCard = () => {
  cardVisible.value = false
  userProfile.value = {}
  isShowSpinner.value = true
}

const isShowSpinner = ref(true)
const showUserProfileCard = async () => {
  cardVisible.value = true
}

const acceptReq = async () => {
  const res = friendService().acceptRequestAndSync({receiver_id: userAction.userInfo.id, sender_id: user_id.value})
  if (res) {
    isShowAcceptDiv.value = false
    isFriend.value = true
  }
}



</script>

<template>
  <teleport to="body">
    <div
        @click.prevent="closeCard"
        v-if="cardVisible"
        class="context-menu-mask"
    ></div>

    <div v-if="cardVisible" :style="{top: cardTop+'px', left: cardLeft+'px'}" class="shadow bg-body profile-card rounded-3 animate__animated animate__fadeIn animate__faster">
      <template v-if="isShowSpinner">
        <div class="w-100 d-flex justify-content-center align-items-center" style="height: 200px">
          <div class="spinner-border text-primary" style="width: 2.5rem; height: 2.5rem" role="status"></div>
        </div>
      </template>

      <template v-else>
        <div class="profile-bg position-relative p-2" :style="{backgroundImage: `url(${host_custom+'/pfp/'+userProfile.avatar})`}">
          <div v-if="!isFriend && userAction.userInfo.id !== user_id && !isSentReq && !isShowAcceptDiv" class="float-end rounded-circle card-btn" @click.prevent="addFriend"><font-awesome-icon :icon="['fas', 'user-plus']" size="sm" /></div>
          <div v-if="isFriend" class="float-end rounded-circle card-btn"><font-awesome-icon :icon="['fas', 'user-check']" size="sm" /></div>
          <div v-if="isShowAcceptDiv" class="float-end d-flex">
            <div title="接受好友请求" @click="acceptReq" class="rounded-circle card-btn text-success"><font-awesome-icon :icon="['fas', 'check']" size="sm" /></div>
            &ensp;
            <div title="忽略" class="rounded-circle card-btn text-danger"><font-awesome-icon :icon="['fas', 'xmark']" size="sm" /></div>
          </div>
          <div v-if="userAction.userInfo.id === user_id" class="float-end rounded-circle card-btn">
            <router-link class="text-white" to="/profile"><font-awesome-icon :icon="['fas', 'pen']" size="sm" /></router-link>
          </div>

          <div v-if="isSentReq" class="float-end rounded-circle card-btn">
            <font-awesome-icon :icon="['fas', 'hourglass-half']" />
          </div>

          <img :src="host_custom+'/pfp/'+userProfile.avatar" alt="User Profile" class="rounded-circle profile-img">
        </div>

        <div class="profile-body px-3">
          <p class="mb-0 username fs-6 fw-bold">{{ userProfile.name }}</p>

          <p style="font-size: 13px" v-if="userProfile.bio">
            {{ userProfile.bio }}
          </p>
          <p class="" style="font-size: 14px"><font-awesome-icon :icon="['fas', 'calendar']" />
            {{  timeToNumber(userProfile.create_time).year +'-'+  timeToNumber(userProfile.create_time).month +'-'+  timeToNumber(userProfile.create_time).month }}</p>
        </div>
      </template>
    </div>
  </teleport>

</template>

<style scoped>
.context-menu-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
}

.profile-card {
  overflow: hidden;
  position: fixed;
  width: 300px;
  max-width: 300px;
  min-width: 300px;
  z-index: 1000;
}

.profile-img {
  border: 5px solid var(--bs-body-bg);
  bottom: 0;
  transform: translateY(50%);
  position: absolute;
  width: 80px;
  height: 80px;
  object-fit: cover;
}

.card-btn {
  transition: none;
  cursor: pointer;
  color: white;
  background-color: var(--card-btn-color);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
}

.card-btn:hover {
  background-color: var(--card-btn-color-hover);
}

.profile-body {
  margin-top: 40px;
}

.profile-bg {
  height: 100px;
  background-size: 100%;
  background-position: center;
}

.username {
  white-space: nowrap;
}
</style>